package chat.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xkh.xkh.R;
import com.google.gson.Gson;
import com.orm.SugarRecord;

import java.util.ArrayList;
import java.util.List;

import chat.adapter.MessageAdapter;
import chat.model.ChatModel;
import chat.network.http.SendMessage;
import inter.ResponseStatus;
import com.xkh.xkh.MyApplication;
import managers.UIHandler;
import model.Message;
import model.MessageNotify;
import model.User;
import utils.TimeUtil;


/**
 * 聊天界面
 * Created by 凯 on 2015/10/29.
 */
public class ChatActivity extends UIHandler.BaseActivity {

    // 标题栏
    TextView tv_title;

    // 发送消息按钮
    Button btn_send;
    // 输入消息
    EditText et_message;
    // 显示消息
    ListView lv_message;

    MessageAdapter messageAdapter = new MessageAdapter();

    ChatModel chatModel = new ChatModel();
    List<Message> messages = new ArrayList<Message>();

    {
        chatModel.setMessages(messages);
        messageAdapter.setMessages(messages);
        messageAdapter.setChatModel(chatModel);
    }

    // 用户
    User user = new User();

    // 刷新控件
    SwipeRefreshLayout swiperefresh;

    // 返回按钮
    Button btn_back;


    // 监听消息
    MyBroadCastReciver myBroadCastReciver;

    // 发送消息响应
    SendMessage.Delegate sendMessageResponse = new SendMessage.Delegate() {
        @Override
        public void onResponse(String response, SendMessage.UserMessages userMessages) {
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            SendMessage.ResponseMessageState responseMessageState = gson.fromJson(response, SendMessage.ResponseMessageState.class);
            if (responseMessageState.getStatus().equals(ResponseStatus.SUCCESS)) {
                Toast.makeText(ChatActivity.this, "发送成功", Toast.LENGTH_SHORT).show();

                // 写入数据库
                save2message(userMessages);
                chatModel.getNew();
                messageAdapter.notifyDataSetChanged();
                lv_message.smoothScrollToPosition(messages.size()-1);
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };

    // 写入数据库
    private void save2message(SendMessage.UserMessages userMessages) {
        Message message = new Message();
        message.setMessage_Type(userMessages.getMessage_Type());
        message.setUserfromid(userMessages.getUser_FromID());
        message.setMessage_Time(userMessages.getMessage_Time());
        message.setUser_ToID(userMessages.getUser_ToID());
        message.setMessage_Content(userMessages.getMessage_Content());
        SugarRecord.save(message);

        // 更新未读消息条目
        List<MessageNotify> messages = SugarRecord.find(MessageNotify.class, "nameid = ? and type = ?", user.getUser_ID(), "8");
        if (!messages.isEmpty())
        {
            MessageNotify messageNotify = messages.get(0);
            messageNotify.setContent(userMessages.getMessage_Content());
            messageNotify.setTime(userMessages.getMessage_Time());
            SugarRecord.save(messageNotify);
        }
        else
        {
            MessageNotify messageNotify = new MessageNotify();
            messageNotify.setTime(userMessages.getMessage_Time());
            messageNotify.setContent(userMessages.getMessage_Content());
            messageNotify.setNameid(user.getUser_ID());
            messageNotify.setRealName(user.getUser_RealName());
            messageNotify.setType("8");
            SugarRecord.save(messageNotify);
        }
    }

    SendMessage sendMessage = new SendMessage();

    {
        sendMessage.setDelegate(sendMessageResponse);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        // 初始化view
        initview();
        initdata();
    }

    private void initdata() {
        user = (User) getIntent().getSerializableExtra("user");
        tv_title.setText(user.getUser_RealName());

        // 访问本地数据
        chatModel.setFriendID(user.getUser_ID());
        chatModel.init();
        messageAdapter.notifyDataSetChanged();

        lv_message.smoothScrollToPosition(messages.size()-1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadCastReciver);
    }

    @Override
    protected void onPause() {
        super.onPause();
        clearNotify();
    }

    // 清除未读消息数目
    private void clearNotify() {
        List<MessageNotify> messages = SugarRecord.findWithQuery(MessageNotify.class, "Select * from MessageNotify where nameid = ? and type = ?", user.getUser_ID(), "8");
        if (!messages.isEmpty())
        {
            MessageNotify messageNotify = messages.get(0);
            messageNotify.setUnread("0");
            SugarRecord.save(messageNotify);
        }
    }

    View.OnClickListener ItemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_send) {
                sendmsg();
                et_message.setText("");
            } else if (v == btn_back) {
                ChatActivity.this.finish();
            }
        }
    };

    // 发送消息
    void sendmsg() {
        // 消息为空
        if (et_message.getText().toString().isEmpty())
            return;
        SendMessage.UserMessages userMessages = new SendMessage.UserMessages();
        userMessages.setMessage_Content(et_message.getText().toString());
        userMessages.setMessage_Time(TimeUtil.currentTime());
        userMessages.setUser_FromID(MyApplication.getOwnUser().getUser_ID());
        userMessages.setUser_ToID(user.getUser_ID());
        userMessages.setMessage_Type("text");
        sendMessage.setUserMessages(userMessages);
        sendMessage.send();
    }

    // 初始化view
    private void initview() {

        tv_title = (TextView) findViewById(R.id.id_tv_title);

        // 刷新控件
        swiperefresh = (SwipeRefreshLayout) findViewById(R.id.id_id_refresh);
        swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                int num = chatModel.getOld();
                messageAdapter.notifyDataSetChanged();
                swiperefresh.setRefreshing(false);
                lv_message.smoothScrollToPosition(num);
            }
        });

        lv_message = (ListView) findViewById(R.id.id_lv_message);
        lv_message.setAdapter(messageAdapter);
        btn_send = (Button) findViewById(R.id.id_btn_send);
        btn_send.setOnClickListener(ItemClick);
        et_message = (EditText) findViewById(R.id.id_et_message);
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(ItemClick);

        // 注册通知
        IntentFilter filter = new IntentFilter("com.whu.administrator.ws.userMessage");
        myBroadCastReciver = new MyBroadCastReciver();
        registerReceiver(myBroadCastReciver,filter);
    }

    // 接收新消息到达的通知
    class MyBroadCastReciver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            chatModel.getNew();
            messageAdapter.notifyDataSetChanged();
            lv_message.smoothScrollToPosition(messages.size()-1);
        }
    }

}
